<template>
    <div class="bg-image">
    <div class="login_box">
        <h2 class="welcome-title">欢 迎 使 用 员 工 订 餐 系 统</h2>
        <el-form :model="loginForm" :rules="rules" ref="loginForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="loginForm.username" style="width: 260px"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="loginForm.password" show-password style="width: 260px"></el-input>
            </el-form-item>
            <el-form-item>
                <el-checkbox v-model="rememberMe">记住我</el-checkbox>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="login" style="width: 150px ; margin-left: 30px">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
    </div>
</template>

<script>
export default {
    name: "Login",
    data(){
        return{
            loginForm:{
                username:'',
                password:''
            },
            rules: {
                username: [
                    {required: true, message: '请输入用户名', trigger: 'blur'},
                    {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
                ],
                password: [
                    {required: true, message: '请输入密码', trigger: 'blur'},
                ]
            },
            rememberMe: false,  //记住我
        }
    },
    methods:{
        login(){
            let self = this;
            this.$refs['loginForm'].validate(valid => {
                if (valid) {
                    this.$http.post('login',self.loginForm).then(res =>{
                        if (res.data.msg === "success"){
                            //存储在sessionStorage中
                            sessionStorage.setItem("user",JSON.stringify(res.data.user))

                            // 使用 Vuex 存储后端返回的 user
                            self.$store.dispatch('setUser',{user:res.data.user})

                            // 处理记住密码功能
                            if (self.rememberMe) {
                                localStorage.setItem('savedUsername', self.loginForm.username);
                                localStorage.setItem('savedPassword', self.loginForm.password);

                                // 设置 cookie 有效期为 10 天,expires 参数用于指定 cookie 的有效期，以 UTC 格式设置
                                const expireDate = new Date();
                                expireDate.setTime(expireDate.getTime() + (10 * 24 * 60 * 60 * 1000)); // 10 天的毫秒数
                                document.cookie = `savedUsername=${self.loginForm.username}; expires=${expireDate.toUTCString()}; path=/`;
                                document.cookie = `savedPassword=${self.loginForm.password}; expires=${expireDate.toUTCString()}; path=/`;
                            } else {
                                localStorage.removeItem('savedUsername');
                                localStorage.removeItem('savedPassword');

                                // 清除 cookie
                                document.cookie = 'savedUsername=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                                document.cookie = 'savedPassword=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                            }

                            //跳转到主页
                            this.$router.push("/home");
                        } else {
                            this.$message.error('用户名或密码错误,请重新检查');
                        }
                    }).catch(error =>{
                        this.$message.error('登录请求失败.请联系管理员');
                        console.log(error);
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        }
    },
    mounted() {
        // 检查 localStorage 中是否保存了用户名和密码
        const savedUsername = localStorage.getItem('savedUsername');
        const savedPassword = localStorage.getItem('savedPassword');

        if (savedUsername && savedPassword) {
            this.loginForm.username = savedUsername;
            this.loginForm.password = savedPassword;
            this.rememberMe = true;
        }
    }
}
</script>

<style scoped>
.login_box {
    width: 400px;
    padding: 20px;
    margin: 0 auto;
    border: 1px solid #ccc;
    border-radius: 10px;
    box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.1);
    background-color: white;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.demo-ruleForm {
    margin-top: 20px;
}

.el-form-item {
    margin-bottom: 20px;
}
.bg-image{
    background: url("../assets/images/background/bgImg.png") no-repeat;
    background-size: 100%;
    height: 100%;
    /* 解决外边距塌陷 */
    overflow: hidden;
}
.welcome-title {
    text-align: center;
    color: #49a0fd;
    margin-bottom: 20px;
    font-size: 24px;
    font-weight: bold;
}
</style>
